package models

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/jinzhu/gorm"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

var db *gorm.DB
var dbConf DBConfig

type CustomClaims struct {
	ClientIP string `json:"ip"`
	MachineID string `json:"mid"`
	jwt.StandardClaims
}

type DBConfig struct {
	DB DBConn `yaml:"db"`
	Cache DBConn `yaml:"cache"`
}

type DBConn struct {
	 Type string `yaml:"type"`
	 ConnStr map[string]string `yaml:"connstr"`
}


func Init(confPath string) (*gorm.DB,error) {
	confStr,err := ioutil.ReadFile(confPath)
	if err != nil{
		return nil,err
	}
	if err := yaml.Unmarshal([]byte(confStr), &dbConf); err != nil {
		return nil,err
	}
	//conf := configs.GetConfig(`\db.yaml`)
	db, err = gorm.Open(dbConf.DB.Type, dbConf.DB.ConnStr["Main"])
	if err == nil{
		if db.HasTable(&User{})==false {
			db.CreateTable(&User{})
		}
	}
	return db,err
}